#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
#include <iostream>
#include <set>
#include <vector>
#include <sstream>

using namespace std;
int N, H;
int states[111][111];
int hops[111][1111];
int len;
int seq[1111];
int dp[111][1111];
short next[111][1111];
short dpseen[111][1111];
int IND;
int doit(int st, int ind) {
  if (ind == len) {
    next[st][ind] = 0;
    return states[st][0];
  }
  int &res = dp[st][ind];
  if (dpseen[st][ind] == IND) return res;
  dpseen[st][ind] = IND;
  // opcion uno, me mantengo aca...
  res = 1000000;
  // opcion 2, trato de cambiar...
  for (int st2 = 1; st2 < N; ++st2) {
    int res2 = states[st][st2] + hops[st2][seq[ind]] + doit(st2, ind+1);
    if (res2 < res) {
      res = res2;
      next[st][ind] = st2;
    }
  }
  return res;
}

void reconstruct(int st, int ind) {
//  cout << st << "  " << ind << "  " << next[st][ind] << endl;
  if (st == 0) return;
  else printf("%d", st);
  if (next[st][ind]) { printf(" "); reconstruct(next[st][ind], ind+1); }
} 

int main() {
  int i,j ,k = 3;
//  for (i = 0; i < 1000000; i ++) for (j = 0 ; j < 10000; ++j) k = k * 2;
  cin >> N >> H;
  for (i = 0; i < N; ++i) for (j = 0; j < N; ++j) cin >> states[i][j];
  for (i = 0; i < N; ++i) for (j = 0; j < H; ++j) cin >> hops[i][j];
// im not sure if this ok with the problem statement...
  string line;
  getline(cin, line);
  getline(cin, line);
    memset(dpseen, -1, sizeof(dpseen));
    IND = 0;
  while( getline(cin, line) ) {
    IND++;
    if (line == "") break;
    istringstream iss(line);
    len = 0;
    int aux;
    while (iss >> seq[len]) len++;
    //llenamos la ultima columna...
    for (j = 1; j < N; ++j) dp[j][len-1] = hops[j][seq[len-1]]+states[j][0],
      next[j][len-1] = 0;
    for (j = len-2; j>=0; --j)
      for (i = 1; i < N; ++i) {
        dp[i][j] = 1000000;
        for (k = 1; k < N; ++k) {
          aux = dp[k][j+1] + states[i][k] + hops[i][seq[j]];
          if (aux < dp[i][j]) {
            dp[i][j] = aux;
            next[i][j] = k;
          }
        }
      }
    int res = 1;
    for (i = 2; i < N; ++i) if (states[0][i]+dp[i][0] <
                                states[0][res]+dp[res][0]) res = i;  
    printf("%d\n", states[0][res]+dp[res][0]); //<< endl;
    reconstruct(res,0); printf("\n");// cout << endl;
  }
  return 0;
}
